package lhc.learn.nio;

import org.apache.commons.io.IOUtils;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;

/**
 * 多路复用服务轮询线程
 * Created by Lihc on 2016/3/24.
 */
public class MultiplexerTimeServer implements Runnable {
    /**
     * 轮询器
     */
    private Selector selector;

    /**
     * channel
     */
    private ServerSocketChannel channel;

    /**
     * 终止标志
     */
    private volatile boolean stop;

    public MultiplexerTimeServer(int port) {
        try {
            selector = Selector.open();
            channel = ServerSocketChannel.open();
            channel.configureBlocking(false);//非阻塞
            channel.socket().bind(new InetSocketAddress(port), 1024);
            channel.register(selector, SelectionKey.OP_ACCEPT);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * stop
     */
    public void stop() {
        this.stop = true;
    }

    /**
     * 线程实际执行方法
     */
    @Override
    public void run() {
        SelectionKey selectionKey = null;
        while (!stop) {
            try {
                selector.select(1000);
                Set<SelectionKey> set = selector.selectedKeys();
                Iterator<SelectionKey> iterator = set.iterator();
                while (iterator.hasNext()) {
                    selectionKey = iterator.next();
                    iterator.remove();
                    System.out.println("get a link");
                    handInput(selectionKey);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //关闭多路复用器， 关闭复用器，复用器会自己将注册在复用器上的资源关闭
        IOUtils.closeQuietly(selector);
    }


    /**
     * 业务处理
     *
     * @param key SelectionKey selected by SelectionKey.OP_ACCEPT
     */
    private void handInput(SelectionKey key) {
        try {
            if (key.isValid()) {
                if (key.isAcceptable()) {
                    ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                    SocketChannel socketChannel = channel.accept();
                    socketChannel.configureBlocking(false);
                    socketChannel.register(selector, SelectionKey.OP_READ);
                }
                if (key.isReadable()) {
                    SocketChannel channel = (SocketChannel) key.channel();
                    ByteBuffer readBuffer = ByteBuffer.allocate(102400);
                    int readByte = channel.read(readBuffer);
                    if (readByte > 0) {
                        readBuffer.flip();
                        byte[] bytes = new byte[readBuffer.remaining()];
                        readBuffer.get(bytes);
                        String body = new String(bytes, "UTF-8");
                        System.out.println(body);
                        byte[] result = new Date().toString().getBytes("UTF-8");
                        ByteBuffer outBuffer = ByteBuffer.allocate(result.length).put(result);
                        outBuffer.flip();
                        channel.write(outBuffer);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (key != null) {
                key.cancel();
                IOUtils.closeQuietly(key.channel());
            }
        }
    }
}
